package com.hzhq.contract.controller;

import com.hzhq.contract.bean.dto.RoleDTO;
import com.hzhq.contract.bean.vo.DepartVO;
import com.hzhq.contract.bean.vo.RoleVO;
import com.hzhq.contract.convert.RoleConvertBasic;
import com.hzhq.contract.result.Result;
import com.hzhq.contract.service.RoleService;
import com.hzhq.contract.status.DefaultValue;
import com.hzhq.contract.util.Page2ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: hzhq1255
 * @mail: hzhq1255@163.com
 * @date: 2021/4/15 20:29
 * @desc:
 */
@Slf4j
@CrossOrigin
@RestController
@ResponseBody
@Api(tags = "角色管理")
@RequestMapping("/api/v1/roles")
public class RoleController {


    @Autowired
    RoleService roleService;

    @ApiOperation(value = "角色列表AllList")
    @RequestMapping(value = "",method = RequestMethod.GET)
    private Result<Object> getAllList(){
        List<RoleVO> roleVOList = roleService.getAllList().stream().map(RoleConvertBasic.INSTANCE::dtoToVo).collect(Collectors.toList());
        return Result.success(roleVOList);
    }

    @ApiOperation(value = "角色列表Page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage",value = "当前页",paramType = "path",dataTypeClass = Integer.class, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize",value = "每页个数",paramType = "path",dataTypeClass = Integer.class, dataType = "Integer")
    })
    @ResponseBody
    @RequestMapping(value = "/page/{currentPage}/pageSize/{pageSize}",method = RequestMethod.GET)
    private Result<Object> getAllPage(@PathVariable("currentPage") @NotNull Integer currentPage,
                                      @PathVariable("pageSize") @NotNull Integer pageSize){

        Page<RoleVO> roleVOPage = roleService.getAllPage(currentPage, pageSize).map(RoleConvertBasic.INSTANCE::dtoToVo);
        return Result.success(Page2ResultUtil.getPageData(roleVOPage));
    }

    @ApiOperation(value = "getOneByRoleId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId",value = "角色id",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/roleId/{roleId}",method = RequestMethod.GET)
    private Result<Object> getOneByRoleId(@PathVariable("roleId") @NotNull String roleId){
        if ( !ObjectId.isValid(roleId)){
            return Result.error("roleId不符合ObjectId的String格式");
        }
        RoleVO roleVO = RoleConvertBasic.INSTANCE.dtoToVo(roleService.getOneByRoleId(roleId));
        if (null == roleVO){
            return Result.error("该 roleId="+roleId+ " 不存在");
        }
        return Result.success(roleVO);
    }

    @ApiOperation(value = "getOneByRoleName")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleName",value = "角色name",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/roleName/{roleName}",method = RequestMethod.GET)
    private Result<Object> getOneByRoleName(@PathVariable("roleName") @NotNull String roleName){
        RoleVO roleVO = RoleConvertBasic.INSTANCE.dtoToVo(roleService.getOneByRoleName(roleName));
        if (null == roleVO){
            return Result.error("该 roleName="+roleName+ " 不存在");
        }
        return Result.success(roleVO);
    }

    @ApiOperation(value = "保存角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleType",value = "roleType",paramType = "query",dataTypeClass = Integer.class, dataType = "Integer"),
            @ApiImplicitParam(name = "roleName",value = "roleName",paramType = "query",dataTypeClass = String.class, dataType = "String"),
    })
    @ResponseBody
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    private Result<Object> save(@RequestParam("roleType") @NotNull Integer roleType,
                                @RequestParam("roleName") @NotNull String roleName){
        if (roleService.getOneByRoleName(roleName) != null){
            return Result.error("roleName="+ roleName + " 已存在");
        }
        if (roleService.getOneByRoleType(roleType) != null){
            return Result.error("roleType="+ roleType + " 已存在");
        }
        RoleDTO saveRoleDTO = roleService.save(RoleDTO.builder().roleName(roleName).roleCode(roleType).deleted(DefaultValue.NOT_DELETED).build());
        if (saveRoleDTO == null){
            return Result.error("保存失败");
        }
        return Result.success(saveRoleDTO.getRoleId().toString());
    }


    private RoleDTO isExistedBeforeSave(List<RoleVO> roleVOList){
        for (RoleVO roleVO: roleVOList){
            RoleDTO name = roleService.getOneByRoleName(roleVO.getRoleName());
            if (  null  != roleVO.getRoleName() && name != null){
                return name;
            }
            RoleDTO type = roleService.getOneByRoleType(roleVO.getRoleCode());
            if (  null  != roleVO.getRoleCode() && type != null){
                return type;
            }
        }
        return null;
    }

    @ApiOperation(value = "保存角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "角色VO",value = "RoleVO",example = "[\n" +
                    "    {\n" +
                    "        \"roleId\": \"\",\n" +
                    "        \"roleType\": 100,\n" +
                    "        \"roleName\": \"test\",\n" +
                    "        \"deleted\": 0\n" +
                    "    }\n" +
                    "]",paramType = "body",dataTypeClass = RoleVO.class, dataType = "RoleVO"),
    })
    @ResponseBody
    @RequestMapping(value = "/saveAll",method = RequestMethod.POST)
    private Result<Object> saveAll(@RequestBody @NotNull List<RoleVO> roleVOList){
        RoleDTO isExistedRole = this.isExistedBeforeSave(roleVOList);
        if (null != isExistedRole){
            return Result.error("添加的角色列表中有角色在数据库里  "+ isExistedRole.toString());
        }
        List<RoleDTO> roleDTOList = roleService.saveAll(roleVOList.stream().map(RoleConvertBasic.INSTANCE::voToDto).collect(Collectors.toList()));
        if (roleDTOList == null){
            return Result.error("保存失败");
        }
        return Result.success(roleDTOList.stream().map(e -> e.getRoleId().toString()).collect(Collectors.toList()));
    }

    @ApiOperation(value = "deleteById")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId",value = "roleId",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/delete/roleId/{roleId}",method = RequestMethod.POST)
    private Result<Object> deleteById(@PathVariable("roleId") @NotNull String roleId){
        if (!ObjectId.isValid(roleId)){
            return Result.error("roleId="+ roleId +" 不符合ObjectId");
        }
        String deleteId = roleService.deleteById(roleId);
        if (deleteId == null){
            return Result.error("roleId="+roleId +" 不存在,删除失败");
        }
        return Result.success(deleteId);
    }

    @ApiOperation(value = "deleteByName")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleName",value = "roleName",paramType = "path",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/delete/roleName/{roleName}",method = RequestMethod.POST)
    private Result<Object> deleteByName(@PathVariable("roleName") @NotNull String roleName){
        String deleteId = roleService.deleteByName(roleName);
        if (deleteId == null){
            return Result.error("roleName="+roleName +" 不存在,删除失败");
        }
        return Result.success(deleteId);
    }

    @ApiOperation(value = "deleteByIds")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleIds",value = "roleIds",example = "roleId1,roleId2",paramType = "query",dataTypeClass = String.class, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteAll",method = RequestMethod.POST)
    private Result<Object> deleteByIds(@RequestParam("roleIds") @NotNull List<String> roleIds){
        for (String roleId: roleIds){
            if (!ObjectId.isValid(roleId)){
                return Result.error("roleId="+ roleId +" 不符合ObjectId");
            }
        }
        List<String>  deleteIds = roleService.deleteAll(roleIds);
        return Result.success(deleteIds);
    }

}
